# -*- coding: utf-8 -*-
import traceback
import datetime
import hashlib

from app.manage.marketManage.common.manage_sql import MarketManageSql
from utils.backcode import ImportError
from app.manage.userManage.common.manage_sql import UserManageSql
from utils.logger import Md_Debug
from utils.db_utils import DbConn
from app.project.common.project_sql import ProjectSql


class MarketEditeDB(object):
    """编辑管理"""
    
    def __init__(self):
        self.db = DbConn()
        self.nowtime = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
    
    def add_customer(self, body):
        """新增客户"""
        try:
            ret = dict()
            customer_name = body.get("customer_name")
            customer_tel = body.get("customer_tel")
            company = body.get("company")
            area = body.get("area")
            source = body.get("source")
            # check parameter
            if not customer_name:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "customer_name is none"
            elif not customer_tel:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "customer_tel is none"
            elif not company:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "company is none"
            elif not area:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "area is none"
            elif not source:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "source is none"
            else:
                param = [customer_name, customer_tel, company, area, source]
                self.db.commit(MarketManageSql.ADD_CUSTOMER, param)
                code = ImportError.IMPORT_CODE_SUCCESS
                message = "success"
        except Exception as e:
            code = ImportError.IMPORT_CODE_EXCEPTION
            message = str(e)
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        ret['response_code'] = code
        ret['response_msg'] = message
        return ret
    
    def creat_user(self, body):
        """创建用户"""
        ret = dict()
        try:
            db = self.db  # DbConn()
            # 0:创建 1：删除
            oper_type = body.get('oper_type', None)
            if oper_type == "0":
                user_name = body.get('user_name', None)
                user_passwd = body.get('user_passwd', None)
                
                # check parameter
                if not user_name:
                    code = ImportError.IMPORT_CODE_INVALID_ARGS
                    message = "user_name is none"
                elif not user_passwd:
                    code = ImportError.IMPORT_CODE_INVALID_ARGS
                    message = "user_passwd is none"
                else:
                    query_back = db.fetch_one(UserManageSql.QUERY_USER, [user_name])
                    if query_back:
                        code = ImportError.IMPORT_CODE_INVALID_ARGS
                        message = "用户已经存在"
                    else:
                        user_passwd = hashlib.sha256(user_passwd).hexdigest()
                        param = [user_name, user_passwd, self.nowtime, 0]
                        db.commit(UserManageSql.CREAT_USER, param)
                        code = ImportError.IMPORT_CODE_SUCCESS
                        message = "success"
            elif oper_type == "1":
                user_id = body.get('user_id', None)
                
                # check parameter
                if not user_id:
                    code = ImportError.IMPORT_CODE_INVALID_ARGS
                    message = "user_id is none"
                else:
                    back_data = db.fetch_one(UserManageSql.USR_IS_ADMIN, [user_id])
                    if back_data['role_name'] == "超级管理员":
                        code = ImportError.IMPORT_CODE_INVALID_ARGS
                        message = "没有删除超级管理员权限"
                    else:
                        if db.commit(UserManageSql.DELETE_USR, [user_id]):
                            code = ImportError.IMPORT_CODE_SUCCESS
                            message = "success"
                        else:
                            code = ImportError.UPDATE_GAME_TYPE
                            message = "commit error"
            else:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "Invalid parameter"
        except Exception as e:
            code = ImportError.IMPORT_CODE_EXCEPTION
            message = str(e)
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        ret['response_code'] = code
        ret['response_msg'] = message
        return ret
    
    def add_project(self,body):
        id = None
        try:
            project_name = body.get("name")
            # check parameter
            if not project_name:
                return None
            else:
                param = [project_name,0,self.nowtime]
                id = self.db.fetch_one(MarketManageSql.ADD_MARKET, param)
        except Exception as e:
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        return id
    
    def add_market_task(self, body):
        """添加任务（市场运营）"""
        ret = dict()
        # 1.添加项目,获得项目id
        project_id = self.add_project(body)
        # 2.将id带入并添加
        if project_id == None:
            ret['response_code'] = ImportError.IMPORT_CODE_INVALID_ARGS
            ret['response_msg'] = "project create error"
            return ret
        
        try:
            market_customer = body.get("market_customer")
            market_create_user = body.get("market_create_user")
            market_source = body.get("market_source")
            
            # check parameter
            if not market_customer:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "market_customer is none"
            elif not market_create_user:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "market_create_user is none"
            elif market_source is None:
                code = ImportError.IMPORT_CODE_INVALID_ARGS
                message = "market_source is none"
            else:
                param = [market_customer,market_create_user, market_source,project_id]
                if self.db.commit(MarketManageSql.ADD_MARKET, param):
                    code = ImportError.IMPORT_CODE_SUCCESS
                    message = "success"
        except Exception as e:
            code = ImportError.IMPORT_CODE_EXCEPTION
            message = str(e)
            Md_Debug.error(traceback.format_exc(e))
            print(traceback.format_exc(e))
        ret['response_code'] = code
        ret['response_msg'] = message
        return ret
